#!/usr/bin/env python3
"""
Element UI 按钮组件示例页面
仿照Element UI官网风格，包含代码展示和复制功能
"""

import sys
import os
import json

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

try:
    from PySide6.QtWidgets import *
    from PySide6.QtCore import *
    from PySide6.QtGui import *
except ImportError:
    try:
        from PyQt6.QtWidgets import *
        from PyQt6.QtCore import *
        from PyQt6.QtGui import *
    except ImportError:
        try:
            from PySide2.QtWidgets import *
            from PySide2.QtCore import *
            from PySide2.QtGui import *
        except ImportError:
            from PyQt5.QtWidgets import *
            from PyQt5.QtCore import *
            from PyQt5.QtGui import *

from element_ui.styles import theme_manager


class CodeDisplayWidget(QWidget):
    """代码显示组件"""
    
    def __init__(self, code_content, title="示例代码", parent=None):
        super().__init__(parent)
        self.code_content = code_content
        self.title = title
        self.is_expanded = False
        self.setup_ui()
    
    def setup_ui(self):
        """设置UI"""
        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        
        # 代码控制栏
        control_bar = self.create_control_bar()
        layout.addWidget(control_bar)
        
        # 代码显示区域
        self.code_area = self.create_code_area()
        self.code_area.hide()  # 初始状态隐藏
        layout.addWidget(self.code_area)
    
    def create_control_bar(self):
        """创建代码控制栏"""
        bar = QWidget()
        bar.setStyleSheet("""
            QWidget {
                background-color: #fafbfc;
                border: 1px solid #ebeef5;
                border-bottom: none;
            }
        """)
        
        layout = QHBoxLayout(bar)
        layout.setContentsMargins(20, 12, 20, 12)
        
        # 展开/收起按钮
        self.toggle_btn = QPushButton("显示代码")
        self.toggle_btn.setStyleSheet("""
            QPushButton {
                background-color: transparent;
                color: #409eff;
                border: none;
                font-size: 14px;
                font-weight: 500;
                padding: 4px 8px;
                text-align: left;
            }
            QPushButton:hover {
                color: #66b1ff;
                text-decoration: underline;
            }
        """)
        self.toggle_btn.clicked.connect(self.toggle_code_display)
        
        # 复制按钮
        self.copy_btn = QPushButton("复制代码")
        self.copy_btn.setStyleSheet("""
            QPushButton {
                background-color: #409eff;
                color: #ffffff;
                border: 1px solid #409eff;
                border-radius: 4px;
                font-size: 12px;
                font-weight: 500;
                padding: 6px 12px;
                outline: none;
            }
            QPushButton:hover {
                background-color: #66b1ff;
                border-color: #66b1ff;
            }
            QPushButton:pressed {
                background-color: #3a8ee6;
                border-color: #3a8ee6;
            }
        """)
        self.copy_btn.clicked.connect(self.copy_code)
        
        layout.addWidget(QLabel(self.title))
        layout.addStretch()
        layout.addWidget(self.toggle_btn)
        layout.addWidget(self.copy_btn)
        
        return bar
    
    def create_code_area(self):
        """创建代码显示区域"""
        area = QWidget()
        area.setStyleSheet("""
            QWidget {
                background-color: #fafbfc;
                border: 1px solid #ebeef5;
                border-top: none;
            }
        """)
        
        layout = QVBoxLayout(area)
        layout.setContentsMargins(0, 0, 0, 0)
        
        # 代码文本区域
        self.code_text = QTextEdit()
        self.code_text.setPlainText(self.code_content)
        self.code_text.setReadOnly(True)
        
        # 设置自适应高度的样式
        self.code_text.setStyleSheet("""
            QTextEdit {
                background-color: #282c34;
                color: #abb2bf;
                border: none;
                font-family: 'Consolas', 'Courier New', monospace;
                font-size: 13px;
                line-height: 1.4;
                padding: 20px;
                selection-background-color: #3e4451;
            }
        """)
        
        # 设置代码高亮
        self.setup_code_highlighting()
        
        # 初始禁用滚动条
        self.code_text.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.code_text.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        
        # 连接文档变化信号，在内容加载后调整高度
        self.code_text.document().documentLayoutChanged.connect(self.on_document_layout_changed)
        
        layout.addWidget(self.code_text)
        
        return area
    
    def on_document_layout_changed(self):
        """文档布局变化时调整高度"""
        # 延迟调整，确保布局完全完成
        QTimer.singleShot(50, self.adjust_code_text_height)
    
    def adjust_code_text_height(self):
        """调整代码文本框高度以适应内容"""
        if not hasattr(self, 'code_text'):
            return
            
        # 暂时设置一个较大的宽度来计算实际需要的高度
        self.code_text.setFixedHeight(16777215)  # 最大高度
        
        # 确保文档宽度正确
        doc = self.code_text.document()
        available_width = self.code_text.viewport().width() - 40  # 减去padding
        doc.setTextWidth(available_width if available_width > 0 else 800)
        
        # 计算所需高度
        content_height = int(doc.size().height())
        
        # 添加padding和边距
        padding_top_bottom = 40  # 20px * 2
        total_height = content_height + padding_top_bottom
        
        # 设置合理的高度限制
        min_height = 120
        max_height = 800  # 增加最大高度限制
        
        # 计算最终高度
        final_height = max(min_height, min(max_height, total_height))
        
        # 应用高度
        self.code_text.setFixedHeight(final_height)
        
        # 如果内容超过最大高度，启用垂直滚动条
        if total_height > max_height:
            self.code_text.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        else:
            self.code_text.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
    
    def setup_code_highlighting(self):
        """设置代码语法高亮"""
        # 根据代码内容判断语言类型
        if self.code_content.strip().startswith('//') or 'import QtQuick' in self.code_content:
            # QML代码
            highlighter = QMLHighlighter(self.code_text.document())
        elif self.code_content.strip().startswith('<!--') or '<template>' in self.code_content:
            # Vue/HTML代码 - 使用Python高亮器的简化版本
            highlighter = PythonHighlighter(self.code_text.document())
        else:
            # Python代码
            highlighter = PythonHighlighter(self.code_text.document())
    
    def toggle_code_display(self):
        """切换代码显示状态"""
        if self.is_expanded:
            self.code_area.hide()
            self.toggle_btn.setText("显示代码")
            self.is_expanded = False
        else:
            self.code_area.show()
            self.toggle_btn.setText("隐藏代码")
            self.is_expanded = True
            
            # 展开时重新调整高度，使用延迟确保显示完成后再调整
            QTimer.singleShot(100, self.adjust_code_text_height)
    
    def resizeEvent(self, event):
        """窗口大小变化事件"""
        super().resizeEvent(event)
        if hasattr(self, 'code_text') and self.is_expanded:
            # 延迟调整高度，确保布局完成后再调整
            QTimer.singleShot(100, self.adjust_code_text_height)
    
    def copy_code(self):
        """复制代码到剪贴板"""
        clipboard = QApplication.clipboard()
        clipboard.setText(self.code_content)
        
        # 显示复制成功提示
        self.show_copy_success()
    
    def show_copy_success(self):
        """显示复制成功提示"""
        # 临时改变按钮文本
        original_text = self.copy_btn.text()
        self.copy_btn.setText("复制成功!")
        self.copy_btn.setStyleSheet("""
            QPushButton {
                background-color: #67c23a;
                color: #ffffff;
                border: 1px solid #67c23a;
                border-radius: 4px;
                font-size: 12px;
                font-weight: 500;
                padding: 6px 12px;
                outline: none;
            }
        """)
        
        # 2秒后恢复原始状态
        QTimer.singleShot(2000, lambda: self.restore_copy_button(original_text))
    
    def restore_copy_button(self, original_text):
        """恢复复制按钮原始状态"""
        self.copy_btn.setText(original_text)
        self.copy_btn.setStyleSheet("""
            QPushButton {
                background-color: #409eff;
                color: #ffffff;
                border: 1px solid #409eff;
                border-radius: 4px;
                font-size: 12px;
                font-weight: 500;
                padding: 6px 12px;
                outline: none;
            }
            QPushButton:hover {
                background-color: #66b1ff;
                border-color: #66b1ff;
            }
            QPushButton:pressed {
                background-color: #3a8ee6;
                border-color: #3a8ee6;
            }
        """)


class QMLHighlighter(QSyntaxHighlighter):
    """QML语法高亮器"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        
        # 定义高亮规则
        self.highlighting_rules = []
        
        # QML关键字高亮
        keyword_format = QTextCharFormat()
        keyword_format.setForeground(QColor("#c678dd"))
        keyword_format.setFontWeight(QFont.Bold)
        
        qml_keywords = [
            'import', 'as', 'property', 'signal', 'function', 'var', 'let', 'const',
            'if', 'else', 'for', 'while', 'switch', 'case', 'default', 'break',
            'continue', 'return', 'try', 'catch', 'finally', 'true', 'false',
            'null', 'undefined', 'console', 'Qt'
        ]
        
        for keyword in qml_keywords:
            pattern = QRegularExpression(f'\\b{keyword}\\b')
            self.highlighting_rules.append((pattern, keyword_format))
        
        # QML组件名高亮
        component_format = QTextCharFormat()
        component_format.setForeground(QColor("#e06c75"))
        component_format.setFontWeight(QFont.Bold)
        
        qml_components = [
            'Row', 'Column', 'Item', 'Rectangle', 'Text', 'Button', 'ElementButton',
            'MouseArea', 'ListView', 'GridView', 'Flickable', 'ScrollView'
        ]
        
        for component in qml_components:
            pattern = QRegularExpression(f'\\b{component}\\b')
            self.highlighting_rules.append((pattern, component_format))
        
        # 属性名高亮
        property_format = QTextCharFormat()
        property_format.setForeground(QColor("#56b6c2"))
        
        pattern = QRegularExpression('\\b[a-zA-Z_][a-zA-Z0-9_]*(?=\\s*:)')
        self.highlighting_rules.append((pattern, property_format))
        
        # 字符串高亮
        string_format = QTextCharFormat()
        string_format.setForeground(QColor("#98c379"))
        self.highlighting_rules.append((QRegularExpression('"[^"]*"'), string_format))
        self.highlighting_rules.append((QRegularExpression("'[^']*'"), string_format))
        
        # 注释高亮
        comment_format = QTextCharFormat()
        comment_format.setForeground(QColor("#5c6370"))
        comment_format.setFontItalic(True)
        
        # 单行注释
        self.highlighting_rules.append((QRegularExpression('//.*'), comment_format))
        
        # 多行注释
        self.multiline_comment_format = comment_format
        self.comment_start_expression = QRegularExpression('/\\*')
        self.comment_end_expression = QRegularExpression('\\*/')
        
        # 数字高亮
        number_format = QTextCharFormat()
        number_format.setForeground(QColor("#d19a66"))
        self.highlighting_rules.append((QRegularExpression('\\b\\d+(\\.\\d+)?\\b'), number_format))
    
    def highlightBlock(self, text):
        """应用高亮规则"""
        # 应用单行规则
        for pattern, format in self.highlighting_rules:
            expression = QRegularExpression(pattern)
            iterator = expression.globalMatch(text)
            while iterator.hasNext():
                match = iterator.next()
                self.setFormat(match.capturedStart(), match.capturedLength(), format)
        
        # 处理多行注释
        self.setCurrentBlockState(0)
        start_index = 0
        if self.previousBlockState() != 1:
            start_match = self.comment_start_expression.match(text)
            start_index = start_match.capturedStart() if start_match.hasMatch() else -1
        
        while start_index >= 0:
            end_match = self.comment_end_expression.match(text, start_index)
            if end_match.hasMatch():
                comment_length = end_match.capturedEnd() - start_index
                self.setFormat(start_index, comment_length, self.multiline_comment_format)
                start_match = self.comment_start_expression.match(text, start_index + comment_length)
                start_index = start_match.capturedStart() if start_match.hasMatch() else -1
            else:
                self.setCurrentBlockState(1)
                self.setFormat(start_index, len(text) - start_index, self.multiline_comment_format)
                break


class PythonHighlighter(QSyntaxHighlighter):
    """Python语法高亮器"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        
        # 定义高亮规则
        self.highlighting_rules = []
        
        # 关键字高亮
        keyword_format = QTextCharFormat()
        keyword_format.setForeground(QColor("#c678dd"))
        keyword_format.setFontWeight(QFont.Bold)
        
        keywords = [
            'and', 'as', 'assert', 'break', 'class', 'continue', 'def',
            'del', 'elif', 'else', 'except', 'finally', 'for', 'from',
            'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or',
            'pass', 'raise', 'return', 'try', 'while', 'with', 'yield',
            'True', 'False', 'None'
        ]
        
        for keyword in keywords:
            pattern = QRegularExpression(f'\\b{keyword}\\b')
            self.highlighting_rules.append((pattern, keyword_format))
        
        # 字符串高亮
        string_format = QTextCharFormat()
        string_format.setForeground(QColor("#98c379"))
        self.highlighting_rules.append((QRegularExpression('".*"'), string_format))
        self.highlighting_rules.append((QRegularExpression("'.*'"), string_format))
        
        # 注释高亮
        comment_format = QTextCharFormat()
        comment_format.setForeground(QColor("#5c6370"))
        comment_format.setFontItalic(True)
        self.highlighting_rules.append((QRegularExpression('#.*'), comment_format))
        
        # 数字高亮
        number_format = QTextCharFormat()
        number_format.setForeground(QColor("#d19a66"))
        self.highlighting_rules.append((QRegularExpression('\\b\\d+\\b'), number_format))
    
    def highlightBlock(self, text):
        """应用高亮规则"""
        for pattern, format in self.highlighting_rules:
            expression = QRegularExpression(pattern)
            iterator = expression.globalMatch(text)
            while iterator.hasNext():
                match = iterator.next()
                self.setFormat(match.capturedStart(), match.capturedLength(), format)


class ElementButton(QPushButton):
    """Element UI 风格按钮组件"""
    
    # 按钮配置 (与之前的实现相同)
    BUTTON_CONFIGS = {
        'default': {
            'normal': {
                'background-color': '#ffffff',
                'color': '#606266',
                'border-color': '#dcdfe6'
            },
            'hover': {
                'background-color': '#ecf5ff',
                'color': '#409eff',
                'border-color': '#c6e2ff'
            },
            'active': {
                'background-color': '#3a8ee6',
                'color': '#ffffff',
                'border-color': '#3a8ee6'
            },
            'disabled': {
                'background-color': '#ffffff',
                'color': '#c0c4cc',
                'border-color': '#ebeef5'
            },
            'plain': {
                'normal': {
                    'background-color': '#ffffff',
                    'color': '#606266',
                    'border-color': '#dcdfe6'
                },
                'hover': {
                    'background-color': '#409eff',
                    'color': '#ffffff',
                    'border-color': '#409eff'
                }
            }
        },
        'primary': {
            'normal': {
                'background-color': '#409eff',
                'color': '#ffffff',
                'border-color': '#409eff'
            },
            'hover': {
                'background-color': '#66b1ff',
                'color': '#ffffff',
                'border-color': '#66b1ff'
            },
            'active': {
                'background-color': '#3a8ee6',
                'color': '#ffffff',
                'border-color': '#3a8ee6'
            },
            'disabled': {
                'background-color': '#a0cfff',
                'color': '#ffffff',
                'border-color': '#a0cfff'
            },
            'plain': {
                'normal': {
                    'background-color': '#ecf5ff',
                    'color': '#409eff',
                    'border-color': '#b3d8ff'
                },
                'hover': {
                    'background-color': '#409eff',
                    'color': '#ffffff',
                    'border-color': '#409eff'
                }
            }
        },
        'success': {
            'normal': {
                'background-color': '#67c23a',
                'color': '#ffffff',
                'border-color': '#67c23a'
            },
            'hover': {
                'background-color': '#85ce61',
                'color': '#ffffff',
                'border-color': '#85ce61'
            },
            'active': {
                'background-color': '#5daf34',
                'color': '#ffffff',
                'border-color': '#5daf34'
            },
            'disabled': {
                'background-color': '#b3e19d',
                'color': '#ffffff',
                'border-color': '#b3e19d'
            },
            'plain': {
                'normal': {
                    'background-color': '#f0f9ff',
                    'color': '#67c23a',
                    'border-color': '#c2e7b0'
                },
                'hover': {
                    'background-color': '#67c23a',
                    'color': '#ffffff',
                    'border-color': '#67c23a'
                }
            }
        },
        'info': {
            'normal': {
                'background-color': '#909399',
                'color': '#ffffff',
                'border-color': '#909399'
            },
            'hover': {
                'background-color': '#a6a9ad',
                'color': '#ffffff',
                'border-color': '#a6a9ad'
            },
            'active': {
                'background-color': '#82848a',
                'color': '#ffffff',
                'border-color': '#82848a'
            },
            'disabled': {
                'background-color': '#c8c9cc',
                'color': '#ffffff',
                'border-color': '#c8c9cc'
            },
            'plain': {
                'normal': {
                    'background-color': '#f4f4f5',
                    'color': '#909399',
                    'border-color': '#d3d4d6'
                },
                'hover': {
                    'background-color': '#909399',
                    'color': '#ffffff',
                    'border-color': '#909399'
                }
            }
        },
        'warning': {
            'normal': {
                'background-color': '#e6a23c',
                'color': '#ffffff',
                'border-color': '#e6a23c'
            },
            'hover': {
                'background-color': '#ebb563',
                'color': '#ffffff',
                'border-color': '#ebb563'
            },
            'active': {
                'background-color': '#cf9236',
                'color': '#ffffff',
                'border-color': '#cf9236'
            },
            'disabled': {
                'background-color': '#f3d19e',
                'color': '#ffffff',
                'border-color': '#f3d19e'
            },
            'plain': {
                'normal': {
                    'background-color': '#fdf6ec',
                    'color': '#e6a23c',
                    'border-color': '#f5dab1'
                },
                'hover': {
                    'background-color': '#e6a23c',
                    'color': '#ffffff',
                    'border-color': '#e6a23c'
                }
            }
        },
        'danger': {
            'normal': {
                'background-color': '#f56c6c',
                'color': '#ffffff',
                'border-color': '#f56c6c'
            },
            'hover': {
                'background-color': '#f78989',
                'color': '#ffffff',
                'border-color': '#f78989'
            },
            'active': {
                'background-color': '#dd6161',
                'color': '#ffffff',
                'border-color': '#dd6161'
            },
            'disabled': {
                'background-color': '#fab6b6',
                'color': '#ffffff',
                'border-color': '#fab6b6'
            },
            'plain': {
                'normal': {
                    'background-color': '#fef0f0',
                    'color': '#f56c6c',
                    'border-color': '#fbc4c4'
                },
                'hover': {
                    'background-color': '#f56c6c',
                    'color': '#ffffff',
                    'border-color': '#f56c6c'
                }
            }
        }
    }
    
    SIZE_CONFIGS = {
        'large': {'height': 40, 'padding': '11px 19px', 'font-size': '14px'},
        'default': {'height': 32, 'padding': '8px 15px', 'font-size': '14px'},
        'small': {'height': 28, 'padding': '6px 11px', 'font-size': '12px'},
        'mini': {'height': 24, 'padding': '4px 7px', 'font-size': '12px'}
    }
    
    def __init__(self, text="", button_type="default", size="default", plain=False, parent=None):
        super().__init__(text, parent)
        self.button_type = button_type
        self.size = size
        self.plain = plain
        self._setup_button()
    
    def _setup_button(self):
        """设置按钮样式"""
        self._apply_style()
        
    def _apply_style(self):
        """应用样式配置到QPushButton"""
        config = self.BUTTON_CONFIGS.get(self.button_type, self.BUTTON_CONFIGS['default'])
        size_config = self.SIZE_CONFIGS.get(self.size, self.SIZE_CONFIGS['default'])
        
        if self.plain and 'plain' in config:
            normal_style = config['plain']['normal']
            hover_style = config['plain']['hover']
            active_style = config['plain']['hover']
        else:
            normal_style = config['normal']
            hover_style = config['hover']
            active_style = config['active']
        
        disabled_style = config['disabled']
        
        style = f"""
            QPushButton {{
                background-color: {normal_style['background-color']};
                color: {normal_style['color']};
                border: 1px solid {normal_style['border-color']};
                border-radius: 4px;
                padding: {size_config['padding']};
                font-size: {size_config['font-size']};
                font-weight: 500;
                font-family: 'Microsoft YaHei', Arial, sans-serif;
                text-align: center;
                outline: none;
            }}
            QPushButton:hover {{
                background-color: {hover_style['background-color']};
                color: {hover_style['color']};
                border-color: {hover_style['border-color']};
            }}
            QPushButton:pressed {{
                background-color: {active_style['background-color']};
                color: {active_style['color']};
                border-color: {active_style['border-color']};
            }}
            QPushButton:disabled {{
                background-color: {disabled_style['background-color']};
                color: {disabled_style['color']};
                border-color: {disabled_style['border-color']};
            }}
        """
        
        self.setStyleSheet(style)
        self.setFixedHeight(size_config['height'])
        self.setMinimumWidth(64)


class DemoSection(QWidget):
    """演示区域组件"""
    
    def __init__(self, title, demo_widget, code_content, parent=None):
        super().__init__(parent)
        self.title = title
        self.demo_widget = demo_widget
        self.code_content = code_content
        self.setup_ui()
    
    def setup_ui(self):
        """设置UI"""
        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 30)
        layout.setSpacing(0)
        
        # 标题
        title_label = QLabel(self.title)
        title_label.setStyleSheet("""
            QLabel {
                font-size: 20px;
                font-weight: 600;
                color: #303133;
                margin-bottom: 15px;
            }
        """)
        layout.addWidget(title_label)
        
        # 演示区域
        demo_container = QWidget()
        demo_container.setStyleSheet("""
            QWidget {
                background-color: #ffffff;
                border: 1px solid #ebeef5;
                border-radius: 4px 4px 0 0;
                padding: 30px;
            }
        """)
        
        demo_layout = QVBoxLayout(demo_container)
        demo_layout.addWidget(self.demo_widget)
        layout.addWidget(demo_container)
        
        # 代码显示组件
        code_display = CodeDisplayWidget(self.code_content, f"{self.title}示例代码")
        layout.addWidget(code_display)


class ElementUIButtonDemo(QMainWindow):
    """Element UI 按钮演示主窗口"""
    
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Element UI 按钮组件演示")
        self.setGeometry(100, 100, 1200, 900)
        self.setup_ui()
    
    def setup_ui(self):
        """设置UI"""
        # 主窗口部件
        main_widget = QWidget()
        self.setCentralWidget(main_widget)
        
        # 主布局
        main_layout = QVBoxLayout(main_widget)
        main_layout.setContentsMargins(0, 0, 0, 0)
        
        # 创建滚动区域
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_area.setStyleSheet("""
            QScrollArea {
                border: none;
                background-color: #f5f7fa;
            }
        """)
        
        # 内容区域
        content_widget = QWidget()
        content_layout = QVBoxLayout(content_widget)
        content_layout.setContentsMargins(40, 40, 40, 40)
        content_layout.setSpacing(40)
        
        # 标题
        title = QLabel("Button 按钮")
        title.setStyleSheet("""
            QLabel {
                font-size: 36px;
                font-weight: 700;
                color: #303133;
                margin-bottom: 20px;
            }
        """)
        content_layout.addWidget(title)
        
        # 描述
        description = QLabel("常用的操作按钮。")
        description.setStyleSheet("""
            QLabel {
                font-size: 16px;
                color: #606266;
                margin-bottom: 30px;
            }
        """)
        content_layout.addWidget(description)
        
        # 基础用法示例
        basic_demo = self.create_basic_demo()
        content_layout.addWidget(basic_demo)
        
        # 朴素按钮示例
        plain_demo = self.create_plain_demo()
        content_layout.addWidget(plain_demo)
        
        # 不同尺寸示例
        size_demo = self.create_size_demo()
        content_layout.addWidget(size_demo)
        
        # 禁用状态示例
        disabled_demo = self.create_disabled_demo()
        content_layout.addWidget(disabled_demo)
        
        content_layout.addStretch()
        
        scroll_area.setWidget(content_widget)
        main_layout.addWidget(scroll_area)
    
    def create_basic_demo(self):
        """创建基础用法演示"""
        demo_widget = QWidget()
        layout = QHBoxLayout(demo_widget)
        layout.setSpacing(15)
        
        button_types = [
            ("默认按钮", "default"),
            ("主要按钮", "primary"),
            ("成功按钮", "success"),
            ("信息按钮", "info"),
            ("警告按钮", "warning"),
            ("危险按钮", "danger")
        ]
        
        for text, btn_type in button_types:
            btn = ElementButton(text, btn_type)
            btn.clicked.connect(lambda checked, t=text: self.on_button_click(t))
            layout.addWidget(btn)
        
        layout.addStretch()
        
        code_content = '''// 基础用法 - QML代码
import QtQuick 2.15
import QtQuick.Controls 2.15
import "../element_ui"

Row {
    spacing: 15
    
    ElementButton {
        text: "默认按钮"
        buttonType: "default"
        onClicked: console.log("默认按钮被点击")
    }
    
    ElementButton {
        text: "主要按钮"
        buttonType: "primary"
        onClicked: console.log("主要按钮被点击")
    }
    
    ElementButton {
        text: "成功按钮"
        buttonType: "success"
        onClicked: console.log("成功按钮被点击")
    }
    
    ElementButton {
        text: "信息按钮"
        buttonType: "info"
        onClicked: console.log("信息按钮被点击")
    }
    
    ElementButton {
        text: "警告按钮"
        buttonType: "warning"
        onClicked: console.log("警告按钮被点击")
    }
    
    ElementButton {
        text: "危险按钮"
        buttonType: "danger"
        onClicked: console.log("危险按钮被点击")
    }
}'''
        
        return DemoSection("基础用法", demo_widget, code_content)
    
    def create_plain_demo(self):
        """创建朴素按钮演示"""
        demo_widget = QWidget()
        layout = QHBoxLayout(demo_widget)
        layout.setSpacing(15)
        
        button_types = [
            ("朴素按钮", "default"),
            ("主要按钮", "primary"),
            ("成功按钮", "success"),
            ("信息按钮", "info"),
            ("警告按钮", "warning"),
            ("危险按钮", "danger")
        ]
        
        for text, btn_type in button_types:
            btn = ElementButton(text, btn_type, plain=True)
            btn.clicked.connect(lambda checked, t=text: self.on_button_click(f"朴素{t}"))
            layout.addWidget(btn)
        
        layout.addStretch()
        
        code_content = '''// 朴素按钮 - QML代码
import QtQuick 2.15
import QtQuick.Controls 2.15
import "../element_ui"

Row {
    spacing: 15
    
    ElementButton {
        text: "朴素按钮"
        buttonType: "default"
        plain: true
        onClicked: console.log("朴素按钮被点击")
    }
    
    ElementButton {
        text: "主要按钮"
        buttonType: "primary"
        plain: true
        onClicked: console.log("朴素主要按钮被点击")
    }
    
    ElementButton {
        text: "成功按钮"
        buttonType: "success"
        plain: true
        onClicked: console.log("朴素成功按钮被点击")
    }
    
    ElementButton {
        text: "信息按钮"
        buttonType: "info"
        plain: true
        onClicked: console.log("朴素信息按钮被点击")
    }
    
    ElementButton {
        text: "警告按钮"
        buttonType: "warning"
        plain: true
        onClicked: console.log("朴素警告按钮被点击")
    }
    
    ElementButton {
        text: "危险按钮"
        buttonType: "danger"
        plain: true
        onClicked: console.log("朴素危险按钮被点击")
    }
}'''
        
        return DemoSection("朴素按钮", demo_widget, code_content)
    
    def create_size_demo(self):
        """创建不同尺寸演示"""
        demo_widget = QWidget()
        layout = QHBoxLayout(demo_widget)
        layout.setSpacing(15)
        
        sizes = [
            ("大型按钮", "large"),
            ("默认按钮", "default"),
            ("小型按钮", "small"),
            ("超小按钮", "mini")
        ]
        
        for text, size in sizes:
            btn = ElementButton(text, "primary", size)
            btn.clicked.connect(lambda checked, t=text: self.on_button_click(t))
            layout.addWidget(btn)
        
        layout.addStretch()
        
        code_content = '''// 不同尺寸 - QML代码
import QtQuick 2.15
import QtQuick.Controls 2.15
import "../element_ui"

Row {
    spacing: 15
    
    ElementButton {
        text: "大型按钮"
        buttonType: "primary"
        buttonSize: "large"
        onClicked: console.log("大型按钮被点击")
    }
    
    ElementButton {
        text: "默认按钮"
        buttonType: "primary"
        buttonSize: "default"
        onClicked: console.log("默认按钮被点击")
    }
    
    ElementButton {
        text: "小型按钮"
        buttonType: "primary"
        buttonSize: "small"
        onClicked: console.log("小型按钮被点击")
    }
    
    ElementButton {
        text: "超小按钮"
        buttonType: "primary"
        buttonSize: "mini"
        onClicked: console.log("超小按钮被点击")
    }
}'''
        
        return DemoSection("不同尺寸", demo_widget, code_content)
    
    def create_disabled_demo(self):
        """创建禁用状态演示"""
        demo_widget = QWidget()
        layout = QHBoxLayout(demo_widget)
        layout.setSpacing(15)
        
        # 正常按钮
        normal_btn = ElementButton("正常按钮", "primary")
        normal_btn.clicked.connect(lambda: self.on_button_click("正常按钮"))
        layout.addWidget(normal_btn)
        
        # 禁用按钮
        disabled_btn = ElementButton("禁用按钮", "primary")
        disabled_btn.setEnabled(False)
        layout.addWidget(disabled_btn)
        
        # 朴素禁用
        plain_disabled = ElementButton("朴素禁用", "success", plain=True)
        plain_disabled.setEnabled(False)
        layout.addWidget(plain_disabled)
        
        layout.addStretch()
        
        code_content = '''// 禁用状态 - QML代码
import QtQuick 2.15
import QtQuick.Controls 2.15
import "../element_ui"

Row {
    spacing: 15
    
    ElementButton {
        text: "正常按钮"
        buttonType: "primary"
        enabled: true
        onClicked: console.log("正常按钮被点击")
    }
    
    ElementButton {
        text: "禁用按钮"
        buttonType: "primary"
        enabled: false
    }
    
    ElementButton {
        text: "朴素禁用"
        buttonType: "success"
        plain: true
        enabled: false
    }
}

// Python中使用示例:
/*
from PySide6.QtWidgets import *
from element_ui.components import ElementButton

# 创建按钮
button = ElementButton("按钮文字", "primary", "default")
button.setEnabled(False)  # 禁用按钮
*/'''
        
        return DemoSection("禁用状态", demo_widget, code_content)
    
    def on_button_click(self, button_name):
        """按钮点击处理"""
        print(f"[按钮点击] {button_name}")
        
        # 显示状态栏消息
        self.statusBar().showMessage(f"✓ {button_name}被点击", 3000)


def main():
    """主函数"""
    app = QApplication(sys.argv)
    
    # 设置应用样式
    app.setStyle('Fusion')
    
    # 设置全局字体
    font = QFont("Microsoft YaHei", 10)
    app.setFont(font)
    
    # 设置应用信息
    app.setApplicationName("Element UI Button Demo")
    app.setApplicationVersion("1.0")
    
    # 创建主窗口
    window = ElementUIButtonDemo()
    window.show()
    
    print("🎉 Element UI 按钮组件演示页面启动成功！")
    print("")
    print("✨ 功能特性：")
    print("  • 🎨 仿照Element UI官网风格设计")
    print("  • 📋 支持代码展示和复制功能")
    print("  • 🔽 可展开/收起代码区域")
    print("  • 🖱️ 一键复制示例代码到剪贴板")
    print("  • 🎯 多种按钮类型和状态演示")
    print("  • 💻 语法高亮的代码显示")
    print("")
    print("📖 使用说明：")
    print("  • 点击'显示代码'按钮展开代码区域")
    print("  • 点击'复制代码'按钮复制代码到剪贴板")
    print("  • 滚动查看所有组件示例")
    
    return app.exec()


if __name__ == "__main__":
    sys.exit(main())
